package com.rjhch.tonglink.client.jms.local_mqcu;

import java.util.Properties;

import javax.jms.Connection;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.jms.ConnectionFactory;
import com.tongtech.tmqi.QueueConnectionFactory;
import com.tongtech.tmqi.Topic;

public class TopicBySetProp {

	public static void main(String[] args) {
		
		
		Connection myConn = null;
		Session mySession = null;
		Topic testTopic = null;
		MessageProducer testProducer = null;
		MessageConsumer testConsumer = null;
		MessageConsumer anotherTestConsumer = null;
		TextMessage testMessage = null;

		try {
			Properties pro=new Properties();
        pro.setProperty("java.naming.factory.initial", "tongtech.jms.jndi.JmsContextFactory");
        pro.setProperty("java.naming.provider.url", "tlqlocal://localhost/qcu1");
        
     
       Context context = new javax.naming.InitialContext(pro);

	   ConnectionFactory testConnFactory = 
            (ConnectionFactory) context.lookup
            ("LocalConnectionFactory");	
			testTopic = (Topic)context.lookup("MyTopic");
			testTopic.setProperty("tmqiTopicSubQueueName", "TLQ.SYS.BROKER.SUB");
			testTopic.setProperty("tmqiTopicPubQueueName", "TLQ.SYS.BROKER.SYN");
			
			
			myConn = testConnFactory.createConnection();
			mySession = myConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
			testProducer = mySession.createProducer(testTopic);
			testConsumer = mySession.createConsumer(testTopic);
			anotherTestConsumer = mySession.createConsumer(testTopic);
			testMessage = mySession	.createTextMessage("TopicPubSub Message");
			myConn.start();
			
			System.out.println("发送消息...");
			testProducer.send(testMessage);
			System.out.println("发送完成...");
			Message msg = testConsumer.receive(1000);
			if(msg != null){
				if(msg instanceof TextMessage){
					TextMessage message = (TextMessage)msg;
					System.out.println("testConsumer收到Text消息:"+message.getText());
				}else{
					System.out.println("testConsumer收到非Text消息.");
				}
			}
			msg = anotherTestConsumer.receive(1000);
			if(msg != null){
				if(msg instanceof TextMessage){
					TextMessage message = (TextMessage)msg;
					System.out.println("anotherTestConsumer收到Text消息..."+message.getText());
				}else{
					System.out.println("anotherTestConsumer收到非Text消息...");
				}
			}else{
				System.out.println("Not Receved Message");
			}

		} catch (Exception jmse) {
			System.out.println("Exception oxxurred :" + jmse.toString());
			jmse.printStackTrace();
		} finally {
			try {
				if (mySession != null) {
					mySession.close();
				}
				if (myConn != null) {
					myConn.close();
				}
			} catch (Exception e) {
				System.out.println("There is some error when Exiting!");
				e.printStackTrace();
			}
		}

	}
}
